<?php

namespace App\Module\Sub;

use App\depository\ManageSecretDep;
use App\depository\PermissionsDep;
use App\depository\RoleHasPermissionsDep;
use App\depository\RolesDep;
use App\depository\SubPermissionsDep;
use App\depository\TeamDictDep;
use App\depository\TeamsDep;
use App\Enum\CommonEnum;
use App\Enum\PermissionsEnum;
use App\Enum\RolesEnum;
use App\Module\BaseModule;
use App\Service\DictService;
use App\depository\SubRolesDep;
use App\depository\SubRoleHasPermissionsDep;
use App\depository\ManageForbiddenDep;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Auth;

class SubForbiddenModule extends BaseModule
{

    public function add($request)
    {
        $param = $request->input();
        $teamId = $request->headers->get('TeamId');
        $user = $request->user();

        $dictDep = new TeamDictDep();
        $resDict = $dictDep->getByTeamId($teamId);
        $rcon = $resDict->first(function ($item) {
            return $item->label == 'RCON地址';
        });

        if (!$rcon) {
            return self::response([], '请联系管理员添加RCON地址', 200);
        }

        $data = [
            'steamid' => $param['steamid'],
            'days' => $param['days'],
            'reason' => $param['reason'],
            'gh_id' => $teamId,
            'user_name' => $request->user()->name,
            'nick_name' => $request->user()->nickname,
            'status' => $param['isDirect'] ? ManageForbiddenDep::STATUS_THREE : ManageForbiddenDep::STATUS_TWO,
//            'start_time' => date("Y-m-d H:i:s"),
//            'end_time' => date("Y-m-d H:i:s", strtotime("+{$param['days']} days"))
        ];

        if ($param['isDirect'] == true) {

            $data['start_time'] = date("Y-m-d H:i:s");
            $data['end_time'] = $param['days'] != 0 ? date("Y-m-d H:i:s", strtotime("+{$param['days']} days")) : "2130-01-01 00:00:00";
        }

        $dep = new ManageForbiddenDep();
        $dep->add($data);

        if ($param['isDirect'] == true) {

            $teamDep = new TeamsDep();
            $resTeam = $teamDep->first($teamId);

            $text = $resTeam->reason ?: '{理由}';
            $str = str_replace('{理由}', $param['reason'], $text);
            $str = str_replace('{名称}', $user->nickname, $str);
            $str = str_replace('{时间}', $param['days'], $str);

            $client = new Client();
            $days = $param['days'] > 0 ? "{$param['days']}d" : 0;
            $url = $rcon->value . "AdminBan {$param['steamid']} {$days} {$str}";

            $response = $client->get($url);

            $body = $response->getBody();
            $bodyStr = (string)$body;
            if (!$bodyStr) {
                return self::response([], '连接失败', 200);
            }
        }

        return self::response();
    }

    public function del($request)
    {
        $param = $request->input();

        $dep = new ManageForbiddenDep();

        $dep->del($param);

        return self::response();
    }

    public function edit($request)
    {
        $param = $request->input();
        $teamId = $request->headers->get('TeamId');
        $param['gh_id'] = $teamId;
        $secretDep = new ManageForbiddenDep();
        $secretDep->edit($param);
        return self::response();
    }

    public function list($request)
    {
        $param = $request->input();
        $param['gh_id'] = $request->headers->get('TeamId');
        $mapDep = new ManageForbiddenDep();
        $resList = $mapDep->list($param);
        $list = $resList->getCollection()->toBase();
        $data['list'] = $list->map(function ($item) {
            return [
                'id' => $item->id,
                'user_name' => $item->user_name,
                'nick_name' => $item->nick_name,
                'steamid' => $item->steamid,
                'days' => $item->days,
                'reason' => $item->reason,
                'status' => $item->status,
                'status_show' => ManageForbiddenDep::STATUS[$item->status],
                'start_time' => $item->start_time,
                'end_time' => $item->end_time,
                'created_at' => $item->created_at->toDateTimeString()
            ];
        });
        $data['page'] = [
            'per_page' => $param['per_page'],
            'current_page' => $param['current_page'],
            'total_page' => $resList->lastPage(),
            'total' => $resList->total(),
        ];
        return self::response($data);
    }

    public function approve($request)
    {

        $param = $request->input();

        $dep = new ManageForbiddenDep();
        $teamId = $request->headers->get('TeamId');
        $user = $request->user();
        $resDetail = $dep->first($param['id']);

        $data = [
            'start_time' => date("Y-m-d H:i:s"),
            'end_time' => $resDetail->days == 0 ? '2130-01-01 00:00:00' : date("Y-m-d H:i:s", strtotime("+{$resDetail->days} days")),
            'status' => ManageForbiddenDep::STATUS_ONE
        ];

        $dep->update($param['id'], $data);


        $dictDep = new TeamDictDep();
        $resDict = $dictDep->getByTeamId($teamId);

        $rcon = $resDict->first(function ($item) {
            return $item->label == 'RCON地址';
        });
        if (!$rcon) {
            return self::response([], '请联系管理员添加RCON地址', 200);
        }
        $teamDep = new TeamsDep();
        $resTeam = $teamDep->first($teamId);

        $text = $resTeam->reason ?: '{理由}';
        $str = str_replace('{理由}', $resDetail->reason, $text);
        $str = str_replace('{名称}', $user->nickname, $str);

        $client = new Client();

        $days = $resDetail->days > 0 ? "{$resDetail->days}d" : 0;
        $url = $rcon->value . "AdminBan {$resDetail->steamid} {$days} {$str}";
        $response = $client->get($url);

        $body = $response->getBody();
        $bodyStr = (string)$body;
        if (!$bodyStr) {
            return self::response([], '连接失败', 200);
        }

        return self::response([], $bodyStr);
    }

    public function refuse($request)
    {

        $param = $request->input();

        $dep = new ManageForbiddenDep();
        $data = [
            'status' => ManageForbiddenDep::STATUS_FOROUR
        ];

        $dep->update($param['id'], $data);

        return self::response();

    }

    public function cancel($request)
    {

        $param = $request->input();

        $dep = new ManageForbiddenDep();
        $data = [
            'status' => ManageForbiddenDep::STATUS_FIVE
        ];

        $dep->update($param['id'], $data);

        return self::response();
    }

    public function query($request)
    {

        $param = $request->input();

        if (empty($param['steamid'])) {
            return self::response([], '请指定SteamId', 100);
        }

        $dep = new ManageForbiddenDep();
        $resList = $dep->getBySteamIdStatus($param['steamid'], [ManageForbiddenDep::STATUS_THREE, ManageForbiddenDep::STATUS_ONE]);

        $teamDep = new TeamsDep();

        $data['list'] = $resList->map(function ($item) use ($teamDep) {
            $resTeam = $teamDep->first($item->gh_id);
            return [
                'team' => $resTeam ? $resTeam->name : CommonEnum::DEFAULT_NULL,
                'id' => $item->id,
                'reason' => $item->reason,
                'start_at' => $item->start_time,
                'end_at' => $item->end_time
            ];
        });

        return self::response($data);

    }

}

